#ifndef _TCP_SERVER_H
#define _TCP_SERVER_H

#include<iostream>
#include<string>
#include<cstring>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<pthread.h>
#include"pthreadPool.hpp"

#define BACKLOG 5
#endif

class tcpServer{
    private:
      int _port;
      int _lsock;
      pthreadPool* pool;
    public:
      tcpServer(int port)
        :_port(port)
      {
          
      }
      void tcpServerInit()
      {
          _lsock = socket(AF_INET,SOCK_STREAM,0);
          
          struct sockaddr_in s;
          
          s.sin_family = AF_INET;
          s.sin_port = htons(_port);
          s.sin_addr.s_addr = (INADDR_ANY); 

          if(  bind(_lsock,(struct sockaddr*)&s,sizeof(s)) < 0)
          {
              std::cerr<< "bind error" <<std::endl;
              exit(1);
          }

          if( listen(_lsock,BACKLOG) < 0 )
          {
              std::cerr<< "listen error" <<std::endl;
              exit(2);
          }
        
          pool = new pthreadPool(5);
          pool ->pthreadPoolInit(); 
      }
private:
      void service(int sock)
      {
           char buffer[128];
           while(true)
           {
              buffer[0] = 0;
              int ret = recv( sock, buffer , sizeof(buffer)-1 , 0);
              if( ret < 0 )
              {
                  std::cerr <<" recv error"<<std::endl;
                  exit(4);
              }
              else if(ret == 0)/*对端关闭了*/
              {
                  std::cerr<<" Client quit" <<std::endl;
                  break;  
              }
              else{
                  buffer[ ret ] = 0;
                  std::cout << buffer <<std::endl;
                  std::string msg = "echo: ";
                  msg += buffer;
                  send(sock , msg.c_str() , (int)msg.size(), 0);
              }
          }
      }
public:
      void start()
      {
        while(true)
        {
            struct sockaddr_in end_point;
            socklen_t len = sizeof(end_point);
            int sock = accept(_lsock , (struct sockaddr*)&end_point,&len);
            
            if(sock < 0)
            {
               std::cerr<<"sock error"<<std::endl;
               continue;
            }
           
            std::cout<<"get a link..."<<std::endl;

            Task* task = new Task(sock);
            pool->Put(task);
        } 
      }
      ~tcpServer()
      {
          close(_lsock);
      }
};
